# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(scatterplot3d)
library(optparse)
library(plyr)
library(tidyverse)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
select(c("SampleID", "ClassNote"))

parent <- "./All_Combinaiton"
createWhenNoExist(parent)

sampleColDf <- read.csv(opt$sc, header = T, stringsAsFactors = F, comment.char = "") %>%
select(c("ClassNote", "col"))

pcDataFileName <- paste0(parent, "/../PCA_Score.csv")
pcData <- read_csv(pcDataFileName) %>%
    rename(SampleID = X1)

head(pcData)

parameterFileName <- paste0(parent, "/../PCA_R2.csv")
parameterData <- read.csv(parameterFileName, header = T, stringsAsFactors = F, comment.char = "")


fileName <- paste0(parent, "/All_PCs_Pairsplot.pdf")

pdf(fileName, width = 8, height = 8)

opar <- par(no.readonly = TRUE)
par(family = "Times")


plotData <- pcData %>%
column_to_rownames("SampleID")

labels <- colnames(plotData) %>%
map_chr(function(x){
    pcStr <- str_replace(x, "p", "PC")
    impo <- parameterData[1, pcStr] * 100
    impoStr <- paste0(impo, "%")
    paste0(pcStr, "\n", impoStr)
})

colorData <- pcData %>%
    left_join(sampleInfo, by = c("SampleID")) %>%
    left_join(sampleColDf, by = c("ClassNote")) %>%
    mutate(pch = group_indices(., ClassNote)) %>%
    mutate_at(vars("pch"), function(x){
        x + 1
    })

colorData
pairs(plotData, labels = labels, col = colorData$col)

par(opar)

dev.off()
